from datetime import datetime

from werkzeug.security import generate_password_hash, check_password_hash

from . import db


class BaseModel(object):
    """模型基类，为每个模型补充创建时间与更新时间"""
    create_time = db.Column(db.DateTime, default=datetime.now)  # 记录的创建时间
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)  # 记录的更新时间


class Category(BaseModel):
    __tablename__ = "info_category"

    id = db.Column(db.Integer, primary_key=True)  # 分类编号
    name = db.Column(db.String(64), nullable=False)  # 分类名
    Investment_list = db.relationship('Investment', backref='category', lazy='dynamic')

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "name": self.name
        }
        return resp_dict


class Investor(BaseModel):
    __tablename__ = 'investor'

    id = db.Column(db.Integer, primary_key=True)  # 投资人id
    name = db.Column(db.String(64), nullable=False)  # 投资人的用户名
    password_hash = db.Column(db.String(128), nullable=False)  # 加密的密码
    mobile = db.Column(db.String(11), unique=True, nullable=False)  # 手机号
    avatar_url = db.Column(db.String(256))  # 用户头像路径
    balance = db.Column(db.Integer, default=0) # 余额
    bank_card = db.Column(db.Integer) # 银行卡号
    card = db.Column(db.Integer) # 身份证号码
    mailbox = db.Column(db.Integer) # 邮箱
    is_admin = db.Column(db.Boolean, default=False)  # 是不是管理员用户




    @property
    def password(self):
        raise AttributeError('当前属性不可读')

    @password.setter
    def password(self, value):
        # self.password_hash = 加密（value）
        self.password_hash = generate_password_hash(value)

    def check_password(self, password):
        """校验密码"""
        return check_password_hash(self.password_hash, password)

class Borrower(BaseModel):
    __tablename__ = 'borrower'
    id = db.Column(db.Integer, primary_key=True)  # 借款人id
    name = db.Column(db.String(64), nullable=False)  # 借款人的名字
    borrower_info =  db.Column(db.String(64)) # 借款人信息
    borrower_work_info =  db.Column(db.String(64)) # 借款人工作情况
    assets_info = db.Column(db.String(64)) # 借款人资产情况
    user_funds = db.Column(db.String(64)) # 借款人资金用途
    date_repayment = db.Column(db.String(64))  # 还款时间
    borrower_year_interest_rate = db.Column(db.Float) # 年利率
    investor_list = db.relationship('Investor',back_populates='borrower', lazy='dynamic')

